const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');


const app = getApp()


// pages/Order/Order.js
Page({

      /**
       * 页面的初始数据
       */
      data: {
        total1:'',
        state:6,
        shop1: '',
        ptid: '',
        gif: '',
        add: '',
        tz: [],
        payfs: '',
        time: '',
        goodsid: '',
        addressId: '',
        address: {
          name: '杨家坪似尘沙杀菌时间',
          address: '九龙坡杨家坪时尚白鸽节女人',
          tel: '123456789'
        },
        checkedAddress: '',
        shop: {
          // name: '水果阿萨杀菌时间100G',
          // data: '8月20日16:00',
          // newprice: 12,
          // oldprice: 60,
          // num: 1
        },
        cartshop: [],
        num: 1,
        total: 0,
        show: true
      },

      total() {
        let cartshop = this.data.cartshop;
        let total = 0;
        for (let i = 0; i < cartshop.length; i++) {
          if (cartshop[i].checked) {
            total += cartshop[i].number * cartshop[i].price
          }
        }
        this.setData({
          cartshop: cartshop,
          total: total.toFixed(2)
        })
      },
      radioChange1: function(e) {
        this.setData({
          payfs: 0,
          gif: 5,
        })
        console.log(this.data.gif)
      },
      radioChange2: function(e) {
        this.setData({
          payfs: 1,
          gif: 13,
        })
        console.log(this.data.gif)
      },
      /**
       * 生命周期函数--监听页面加载
       */
      onLoad: function(options) {
        console.log(options)

        this.setData({
          goodsid: options.goodsid,
          ptid: options.id,
          state: options.state
        })
        // this.allTz()
      },
      //购物车
      selct() {
        this.setData({
          show: false
        })
        let that = this
        util.request(api.Select, {}, 'post', {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          'X-Qxmall-Token': wx.getStorageSync('token')
        }).then(function(res) {
          console.log(res)
          that.setData({
            cartshop: res.data.cartList,
            show: false
          });
          that.total()
        });
        console.log('ajsnujkdnakjdnasjkdnakjdnakjdnkajdk')
      },

      //单个商品购买
      getdetail() {
        let that = this
        util.request(api.GoodsDetail, {
          id: that.data.goodsid
        }, 'post', {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          'X-Qxmall-Token': wx.getStorageSync('token')
        }).then(function(res) {
          console.log(res)
          if (res.code == 200) {
            that.setData({
              shop: res.data.commodity,
              total: res.data.commodity.sellingPrice,
            });
          } else {
            that.setData({
              show: false
            })
          }
        });
      },

      //pt物品
      getdetail2() {
        let that = this
        util.request(api.QueryGroupIdInfo + "?id=" + that.data.ptid, {}, 'get', {}).then(function(res) {
          console.log(res)
          that.setData({
            shop1: res.data.groupInfo,
            total1: res.data.groupInfo.originalPrice,
            total2: res.data.groupInfo.nowPrice
          })
        });
      },



      getadress() {
        wx.navigateTo({
          url: '../ neartz/ neartz',
        })
      },
      selectAddress() {
        if (app.globalData.hasLogin == true) {
          wx.navigateTo({
            url: '/pages/ucenter/adress/adress',
          })
        } else {
          wx.navigateTo({
            url: '/pages/login/login',
          })

        }
      },
      /**
       * 生命周期函数--监听页面初次渲染完成
       */
      onReady: function() {

      },

      /**
       * 生命周期函数--监听页面显示
       */
      onShow: function(options) {
        if (this.data.goodsid == undefined&&this.state!=6){
          this.getdetail2()
        }
        
        this.tzresult()
        console.log(this.data.goodsid)
        if (this.data.goodsid == undefined) {
          this.selct()
        } else {
          this.getdetail()
        }
        var time = util.formatTime(new Date())
        this.setData({
          time: time
        })
        var addressId = wx.getStorageSync('addressId');
        if (addressId === "") {
          return false
        }
        this.setData({
          addressId: addressId
        })
        let that = this
        util.request(api.AddressDetail, {
          id: addressId
        }, 'get', {
          'Content-Type': 'application/json',
          'X-Qxmall-Token': wx.getStorageSync('token')
        }).then(function(res) {
          console.log("aaa" + res)
          that.setData({
            checkedAddress: res.data.addressDetail
          })
        });
        console.log("sassa" + that.data.goodsid)


      },
      // 提交订单
      pay() {
        console.log(this.data.payfs)
        if (this.data.checkedAddress.id == '') {
          wx.navigateTo({
            url: '/pages/login/login',
          })
          return false
        }
        let that = this
        if (that.data.payfs === '') {
          wx.showToast({
            title: '请填写支付方式',
            icon: 'none'
          })
          return false
        }
        if (that.data.shop.id) {
          if (that.data.payfs === 0) {
            util.request(api.Submit, {
              commodityId: that.data.shop.id,
              addressId: that.data.checkedAddress.id,
              commNum: that.data.num,
              chief: that.data.tz[0].id,
              pickgoodsTime: that.data.time,
              is_dikou: 0,
              payMethod: that.data.payfs
            }, 'post', {
              'Content-Type': 'application/json',
              'X-Qxmall-Token': wx.getStorageSync('token')
            }).then(function(res) {
              console.log(res)
              if (res.code === 200) {
                const orderSn = res.data.id
                const bb = res.data.orderSn
                const payParam = res.data.payment;
                console.log("支付过程开始");
                wx.requestPayment({
                  'timeStamp': payParam.timeStamp,
                  'nonceStr': payParam.nonceStr,
                  'package': payParam.packageValue,
                  'signType': payParam.signType,
                  'paySign': payParam.paySign,
                  'success': function(res) {
                    console.log("支付过程成功");
                    wx.redirectTo({
                      url: '/pages/ucenter/payresult/payresult?status=1&orderSn=' + orderSn + '&bb=' + bb
                    });
                  },
                  'fail': function(res) {
                    console.log("支付过程失败");
                    wx.redirectTo({
                      url: '/pages/ucenter/payresult/payresult?status=0&orderSn=' + orderSn + '&bb=' + bb
                    });
                  },
                  'complete': function(res) {
                    console.log("支付过程结束")
                  }
                });
              } else {
                wx.showModal({
                  title: '错误提示',
                  content: '订单提交失败',
                  showCancel:false
                })
                // wx.redirectTo({
                //   url: '/pages/ucenter/payresult/payresult?status=0&orderSn=' + orderSn + '&bb=' + bb
                // });
              }
            });

          }
          if (that.data.payfs === 1) {
            util.request(api.Submit, {
              commodityId: that.data.shop.id,
              addressId: that.data.checkedAddress.id,
              commNum: that.data.num,
              chief: that.data.tz[0].id,
              pickgoodsTime: that.data.time,
              is_dikou: 0,
              payMethod: that.data.payfs
            }, 'post', {
              'Content-Type': 'application/json',
              'X-Qxmall-Token': wx.getStorageSync('token')
            }).then(function(res) {
              console.log(res)
              if (res.code === 200) {
                const orderSn = res.data.id
                const bb = res.data.orderSn
                console.log("支付过程开始");
                wx.redirectTo({
                  url: '/pages/ucenter/payresult/payresult?status=1&orderSn=' + orderSn + '&bb=' + bb
                });
              } else {
                // wx.redirectTo({
                //   url: '/pages/ucenter/payresult/payresult?status=0&orderSn=' + orderSn + '&bb=' + bb
                // });
                wx.showModal({
                  title: '错误提示',
                  content: '订单提交失败',
                  showCancel: false
                })
              }
            });

          }
        } else {
          console.log('购物车购买')
          console.log(that.data.cartshop)
          let cart = that.data.cartshop;
          let str = ''
          for (let i = 0; i < cart.length; i++) {
            if (cart[i].checked) {
              // let df={
              //   checked:cart[i].checked,
              //   commodityId: cart[i].commodityId,
              //   id: cart[i].id,
              // }
              console.log(cart[i].id)
              if (str === '') {
                str = str.concat(cart[i].id)
              } else {
                str = str.concat(',' + cart[i].id)
              }

            }
            console.log('aaa' + str)
          }
          if (that.data.payfs == 0) {
            util.request(api.Submit, {
              addressId: that.data.checkedAddress.id,
              cartId: str,
              chief: that.data.tz[0].id,
              pickgoodsTime: that.data.time,
              is_dikou: 0,
              payMethod: that.data.payfs
            }, 'post', {
              'Content-Type': 'application/json',
              'X-Qxmall-Token': wx.getStorageSync('token')
            }).then(function(res) {
              console.log(res)
              if (res.code === 200) {
                const orderSn = res.data.id
                const bb = res.data.orderSn
                const payParam = res.data.payment;
                console.log("支付过程开始");
                wx.requestPayment({
                  'timeStamp': payParam.timeStamp,
                  'nonceStr': payParam.nonceStr,
                  'package': payParam.packageValue,
                  'signType': payParam.signType,
                  'paySign': payParam.paySign,
                  'success': function(res) {
                    console.log("支付过程成功");
                    wx.redirectTo({
                      url: '/pages/ucenter/payresult/payresult?status=1&orderSn=' + orderSn + '&bb=' + bb
                    });
                  },
                  'fail': function(res) {
                    console.log("支付过程失败");
                    wx.redirectTo({
                      url: '/pages/ucenter/payresult/payresult?status=0&orderSn=' + orderSn + '&bb=' + bb
                    });
                  },
                  'complete': function(res) {
                    console.log("支付过程结束")
                  }
                });
              } else {
                wx.showModal({
                  title: '错误提示',
                  content: '订单提交失败',
                  showCancel: false
                })
                // wx.redirectTo({
                //   url: '/pages/ucenter/payresult/payresult?status=0&orderSn=' + orderSn + '&bb=' + bb
                // });
              }
            });


          }
          if (that.data.payfs == 1) {
            wx.showToast({
              title: '购物车内物品站不支持货到付款',
              icon: 'none'
            })
          }
        }
      },

      // 第一次进来的团长
      allTz() {
        let that = this
        util.request(api.QueryNearbyLeader + 'latitude=' + 1 + "&longitude=" + 1, {

        }, 'get', {
          'Content-Type': 'application/json;charset=UTF-8',
          'X-Qxmall-Token': wx.getStorageSync('token')
        }).then(function(res) {
          console.log(res)
          if (res.code == 200) {
            that.setData({
              tz: res.data.leaderList
            })
          }
        });
      },
      //选择团长
      tzresult() {
        this.setData({
          add: []
        })
        var name = wx.getStorageSync('name')
        if (wx.getStorageSync('name')) {
          let that = this
          util.request(api.NearGroup, {
            name: name
          }, 'post', {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'X-Qxmall-Token': wx.getStorageSync('token')
          }).then(function(res) {
            console.log(res)
            let art = res.data.leaderList
            let add = that.data.add
            add.push(res.data.leaderList)
            console.log(add)
            that.setData({
              tz: add
            })

          });
        } else {
          this.allTz()
        }

      },
      showModal(e) {
        if (this.data.checkedAddress == undefined || this.data.checkedAddress == '') {
          wx.showToast({
            title: '先填写购物地址',
            icon: 'none'
          })

        } else {
          this.setData({
            modalName: e.currentTarget.dataset.target
          })
        }

      },
      hideModal(e) {
        this.setData({
          modalName: null
        })
      },

      /**
       * 生命周期函数--监听页面隐藏
       */
      onHide: function() {

      },

      /**
       * 生命周期函数--监听页面卸载
       */
      onUnload: function() {

      },

      /**
       * 页面相关事件处理函数--监听用户下拉动作
       */
      onPullDownRefresh: function() {

      },

      /**
       * 页面上拉触底事件的处理函数
       */
      onReachBottom: function() {

      },

      add() {
        this.setData({
          num: this.data.num + 1,
          total: this.data.shop.sellingPrice * (this.data.num + 1)
        })
        // let shop = this.data.shop
        // let num = shop.num
        // num = num + 1
        // shop.num = num
        // this.setData({
        //   shop: shop,
        //   total: num * this.data.shop.newprice
        // })
      },

      delete() {
        if (this.data.num <= 1) {
          return false
        }
        this.setData({
          num: this.data.num - 1,
          total: this.data.shop.sellingPrice * (this.data.num - 1)
        })
        // if (this.data.shop.num <= 1) {
        //   return false
        // }
        // let shop = this.data.shop
        // let num = shop.num
        // num = num - 1
        // shop.num = num
        // this.setData({
        //   shop: shop,
        //   total: num * this.data.shop.newprice
        // })
      },

      add3() {
        this.setData({
          num: this.data.num + 1,
          total1: this.data.shop1.originalPrice * (this.data.num + 1)
        })
        // let shop = this.data.shop
        // let num = shop.num
        // num = num + 1
        // shop.num = num
        // this.setData({
        //   shop: shop,
        //   total: num * this.data.shop.newprice
        // })
      },

      delete3() {
        if (this.data.num <= 1) {
          return false
        }
        this.setData({
          num: this.data.num - 1,
          total1: this.data.shop1.originalPrice * (this.data.num - 1)
        })
        // if (this.data.shop.num <= 1) {
        //   return false
        // }
        // let shop = this.data.shop
        // let num = shop.num
        // num = num - 1
        // shop.num = num
        // this.setData({
        //   shop: shop,
        //   total: num * this.data.shop.newprice
        // })
      },
      //拼团支付
      pay1() {
        let that = this
        if (that.data.shop1.id) {
            util.request(api.Submit, {
              commodityId: that.data.shop1.commId,
              addressId: that.data.checkedAddress.id,
              commNum: that.data.num,
              chief: that.data.tz[0].id,
              pickgoodsTime: that.data.time,
              is_dikou: 0,
              payMethod: 0
            }, 'post', {
              'Content-Type': 'application/json',
              'X-Qxmall-Token': wx.getStorageSync('token')
            }).then(function(res) {
              console.log(res)
              if (res.code === 200) {
                const orderSn = res.data.id
                const bb = res.data.orderSn
                const payParam = res.data.payment;
                console.log("支付过程开始");
                wx.requestPayment({
                  'timeStamp': payParam.timeStamp,
                  'nonceStr': payParam.nonceStr,
                  'package': payParam.packageValue,
                  'signType': payParam.signType,
                  'paySign': payParam.paySign,
                  'success': function(res) {
                    console.log("支付过程成功");
                    wx.redirectTo({
                      url: '/pages/ucenter/payresult/payresult?status=1&orderSn=' + orderSn + '&bb=' + bb
                    });
                  },
                  'fail': function(res) {
                    console.log("支付过程失败");
                    wx.redirectTo({
                      url: '/pages/ucenter/payresult/payresult?status=0&orderSn=' + orderSn + '&bb=' + bb
                    });
                  },
                  'complete': function(res) {
                    console.log("支付过程结束")
                  }
                });
              } else {
                wx.showModal({
                  title: '错误提示',
                  content: '订单提交失败',
                  showCancel: false
                })
                // wx.redirectTo({
                //   url: '/pages/ucenter/payresult/payresult?status=0&orderSn=' + orderSn + '&bb=' + bb
                // });
              }
            });
        }},
  pay2() {
    let that = this
    if (that.data.shop1.id) {
      util.request(api.Submit, {
        commodityId: that.data.shop1.commId,
        addressId: that.data.checkedAddress.id,
        commNum: 1,
        chief: that.data.tz[0].id,
        pickgoodsTime: that.data.time,
        is_dikou: 0,
        payMethod: 0,
        group: { groupId: that.data.shop1.id, createUserId: "" }
      }, 'post', {
          'Content-Type': 'application/json',
          'X-Qxmall-Token': wx.getStorageSync('token')
        }).then(function (res) {
          console.log(res)
          if (res.code === 200) {
            const orderSn = res.data.id
            const bb = res.data.orderSn
            const payParam = res.data.payment;
            console.log("支付过程开始");
            wx.requestPayment({
              'timeStamp': payParam.timeStamp,
              'nonceStr': payParam.nonceStr,
              'package': payParam.packageValue,
              'signType': payParam.signType,
              'paySign': payParam.paySign,
              'success': function (res) {
                console.log("支付过程成功");
                wx.redirectTo({
                  url: '/pages/ucenter/payresult/payresult?status=1&orderSn=' + orderSn + '&bb=' + bb
                });
              },
              'fail': function (res) {
                console.log("支付过程失败");
                wx.redirectTo({
                  url: '/pages/ucenter/payresult/payresult?status=0&orderSn=' + orderSn + '&bb=' + bb
                });
              },
              'complete': function (res) {
                console.log("支付过程结束")
              }
            });
          } else {
            wx.showModal({
              title: '错误提示',
              content: '订单提交失败',
              showCancel: false
            })
            // wx.redirectTo({
            //   url: '/pages/ucenter/payresult/payresult?status=0&orderSn=' + orderSn + '&bb=' + bb
            // });
          }
        });
    }
  },



          /**
           * 用户点击右上角分享
           */
          onShareAppMessage: function() {

          }
        })